package com.fzebu.fastboot.docs.file.impl;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.fzebu.fastboot.docs.file.AbstractConvert;
import com.fzebu.fastboot.docs.file.FileHandler;
import com.fzebu.fastboot.docs.file.FileType;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/1/20 14:04
 */
public class Image2PDF extends AbstractConvert {

    private final Document document;

    public Image2PDF() {
        this.document = new Document();
        // step1: 创建一个document对象
        document.setMargins(0, 0, 0, 0);
    }

    public Image2PDF(Document document) {
        this.document = document;
    }

    @Override
    public void convert(FileHandler.Builder builder) throws IOException, DocumentException {
        if (!builder.checkFiles()) {
            return;
        }
        File destFile = new File(builder.getDestPath() + "." + FileType.PDF.getType());
        // step2: 创建一个 PdfWriter实例
        PdfWriter.getInstance(document, new FileOutputStream(destFile));
        // step3: 打开文档
        document.open();
        Image img;
        // step4: 在文档中添加图片
        for (File file : builder.getFiles()) {
            if (!this.checkFileType(FileType.IMAGE, file)) {
                continue;
            }
            img = Image.getInstance(file.getPath());
            img.setAlignment(Image.ALIGN_CENTER);
            // 根据图片大小设置页面，先设置页面再newPage
            document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
            document.newPage();
            document.add(img);
        }
        // step5: 关闭文档
        document.close();
    }
}
